package com.muaz;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;

import com.muaz.ObserverService.GetActivityReceiver;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.telephony.SmsManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class HantarSMS extends Activity {
    /** Tag string for our debug logs */
    private static final String TAG = "-HantarSMS ---";

    // Intent filter
    public static final String ACTION_SMS_SENT = "com.muaz.SMS_SENT_ACTION";

    // Related variables
    public Pemantau mPemantau;
    public File sdcard = Environment.getExternalStorageDirectory();
    public String FOLDER_NAME = "bluetooth";
    public String DATA_NAME = "hantarsms-data.txt";
    public String FOLDER_PATH = sdcard.toString() + "/"+FOLDER_NAME;
    public String DATA_PATH = sdcard.toString() + "/"+FOLDER_NAME+"/"+DATA_NAME;
    


    // variable to refer to SharedPreferences
    public SharedPreferences preferences;

    // variables to refer to widgets
    public EditText recipientTextEdit;
    public EditText contentTextEdit;
    public TextView statusView;
    public Button sendButton;
    public Button loadButton;
    

		
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // Super
    	Log.i(TAG, DATA_PATH);
    	super.onCreate(savedInstanceState);
    	preferences = PreferenceManager.getDefaultSharedPreferences(this);
    	
    	// Set up observer
    	mPemantau = new Pemantau(FOLDER_PATH, this);
    	mPemantau.startWatching();
    	
    	// Set up widgets variables so they refer to corresponding widgets
        setContentView(R.layout.main);
        recipientTextEdit = (EditText) HantarSMS.this
                .findViewById(R.id.sms_recipient);
        contentTextEdit = (EditText) HantarSMS.this
                .findViewById(R.id.sms_content);
        statusView = (TextView) HantarSMS.this.findViewById(R.id.sms_status);
        sendButton = (Button) findViewById(R.id.sms_send_message);
        loadButton =(Button) HantarSMS.this.findViewById(R.id.load_manual);
        loadButton.requestFocus();
        
        // Disable editing of the text fields
        recipientTextEdit.setEnabled(false);
        contentTextEdit.setEnabled(false);

    	// Load data.txt file as the sms content and the phone number (preferences)
        updateIsiSms();
    	loadDataToTextFields();
    	
    	// Set the method for loadButton
    	// Reload data from preferences.xml to text fields
    	loadButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				loadDataToTextFields();
			}
		});
    	
        // Set method for send button 
    	// Manually send SMS to phone number
        sendButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            	loadDataToTextFields();
            	sendSMS();
            }
        });

        // Register broadcast receivers for SMS sent and delivered intents
        // Watch for outcome of SMS sent, weather sent, failed, etc.
        registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String message = null;
                boolean error = true;
                
                // Pretty self-explanatry here
                switch (getResultCode()) {
                case Activity.RESULT_OK:
                    message = "Message sent!";
                    error = false;
                    break;
                case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                    message = "Error.";
                    break;
                case SmsManager.RESULT_ERROR_NO_SERVICE:
                    message = "Error: No service.";
                    break;
                case SmsManager.RESULT_ERROR_NULL_PDU:
                    message = "Error: Null PDU.";
                    break;
                case SmsManager.RESULT_ERROR_RADIO_OFF:
                    message = "Error: Radio off.";
                    break;
                }
                

                statusView.setText(message);
                statusView.setTextColor(error ? Color.RED : Color.GREEN);
            }
        }, new IntentFilter(ACTION_SMS_SENT));
    
    }

    // Inflate options menu when Menu button is pressed
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	MenuInflater inflater = getMenuInflater();
    	inflater.inflate(R.menu.menu, menu);
    	return  true;
    }
    
    // Set method when options item is selected after opening options menu
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.open_preferences:     
            	// Launch preferences when "Preference" is pressed
            	Intent settingsActivity = new Intent(HantarSMS.this, Preferences.class);
           		startActivity(settingsActivity);
        		
                   break;

        }
        return true;
    }
    
    // Manually load phone number and hantarsms-data.txt to the text fields 
    public void loadDataToTextFields() {
    	
    	recipientTextEdit.setText(preferences.getString("nombor_penerima", "?"));
    	contentTextEdit.setText(preferences.getString("isi_sms", "kosong"));
    	//getStringFromData()
    }
 
    // Method to read hantarsms-data.txt
    public void updateIsiSms() {
    	// Try to read file
    	File dataFile = new File(DATA_PATH);
    	StringBuilder text = new StringBuilder();
    	if (!dataFile.exists()) {
    		Toast.makeText(HantarSMS.this, "hantarsms-data.txt not found. isi-sms not updated.",
					Toast.LENGTH_LONG).show();
    		Log.i(TAG,"using old data" );
    		return;
    	}

    	try {
    	    BufferedReader br = new BufferedReader(new FileReader(dataFile));
    	    String line;

    	    while ((line = br.readLine()) != null) {
    	        text.append(line);
    	        text.append('\n');
    	    }
    	}
    	catch (IOException e) {
    		Toast.makeText(HantarSMS.this, "hantarsms-data.txt not found. isi-sms not updated.",
    						Toast.LENGTH_LONG).show();
    	    Log.i(TAG,"using old data" );
    	    return;
    	}
    	SharedPreferences.Editor prefsEditor = preferences.edit();
        prefsEditor.putString("isi_sms", text.toString());
        prefsEditor.commit();
    }
    
    // The SMS sending method
    // First it checks the keys in preferences.xml, to make sure whether they are valid
    // Then SmsManager  is used to send the sms
    ///
    public void sendSMS() {
    	if (!preferences.getBoolean("betul2_hantarsms",false)) {
    		Toast.makeText(HantarSMS.this, "Tolong uncheck 'betul2 hantar sms di prefs'", 
    				Toast.LENGTH_LONG).show();
    		return;
    	}
	   
	   
    	if (TextUtils.isEmpty(preferences.getString("nombor_penerima", ""))) {
    		Toast.makeText(HantarSMS.this, "Please enter a message recipient.",
    				Toast.LENGTH_SHORT).show();
    		return;
    	}

    	if (TextUtils.isEmpty(preferences.getString("isi_sms", "kosong"))) {
    		Toast.makeText(HantarSMS.this, "Please enter a message body.",
    				Toast.LENGTH_SHORT).show();
    		return;
    	}
       
    	SmsManager sms = SmsManager.getDefault();
    	
    	// divide the messages, get the recipient number
    	List<String> messages = sms.divideMessage(preferences.getString("isi_sms", "kosong"));
    	String recipient = preferences.getString("nombor_penerima", "");
    	
    	// send the sms
    	for (String message : messages) {
    		sms.sendTextMessage(recipient, null, message, PendingIntent.getBroadcast(
    				HantarSMS.this, 0, new Intent(ACTION_SMS_SENT), 0), null);
    	}
       
    	Toast.makeText(HantarSMS.this, "New Sms sent! Contents: " + preferences.getString("isi_sms", "kosong"),
    			Toast.LENGTH_LONG).show();
    }
   
    public void deleteDataFile() {
    	File dataFile = new File(DATA_PATH);
    	if (!dataFile.exists()) {
    		return;
    	}
    	boolean deleted = dataFile.delete();
    	Log.i(TAG,preferences.getString("isi_sms", "kosong"));
    }


   
}
   
   

